package com.cml.domain.factory;

import com.cml.common.constant.MessageType;
import com.cml.domain.entity.Message;
import org.apache.log4j.Logger;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.nio.ByteBuffer;

/**
 * 姓名：陈茂林
 * 时间：2023/10/11 8:38
 * 描述：
 */
public abstract class MessageBuilderFactory {


    private static Logger logger = Logger.getLogger(MessageBuilderFactory.class);



    public static Message buildMessage(Socket socket) throws IOException {
//        logger.info("获取"+socket.getRemoteSocketAddress()+"消息");
        DataInputStream dataInputStream = new DataInputStream(socket.getInputStream());
        DataOutputStream dataOutputStream= new DataOutputStream(socket.getOutputStream());
        Integer type = dataInputStream.readInt();
        MessageBuilderFactory messageBuilderFactory = getMessageBuilderFactory(type);

        if(messageBuilderFactory!= null){
            Message message =  messageBuilderFactory.doBuildMessage(dataInputStream);
            return message;
        }
        return  null;
    }



    public static MessageBuilderFactory getMessageBuilderFactory(Integer type){
        MessageBuilderFactory messageBuilderFactory = null;
        if(MessageType.CONN_MESSAGE == type){
            messageBuilderFactory= new RemoteServerNodeMessageBuilderFactory();

        } else if (MessageType.VOTE == type) {
            messageBuilderFactory= new VoteMessageBuilderFactory();
        }else if(MessageType.DEFAULT_MESSAGE==type){
            messageBuilderFactory=new DefaultMessageBuilderFactory();
        }
        return messageBuilderFactory;
    }

    public abstract Message doBuildMessage(DataInputStream dataInputStream) throws IOException;

    public static  ByteBuffer buildByteBuffer(Message message) throws IOException {
        ByteBuffer byteBuffer=ByteBuffer.allocate(512);
        byteBuffer.putInt(message.getMessageType());
        MessageBuilderFactory messageBuilderFactory = getMessageBuilderFactory(message.getMessageType());
        messageBuilderFactory.doMessageBuilder(byteBuffer,message);
        //如果不处理，会出现空消息
        int dataLength = byteBuffer.position();
        byteBuffer.flip();
        byte[] bytes=new byte[dataLength];
        byteBuffer.get(bytes);

        ByteBuffer realByteBuffer=ByteBuffer.allocate(dataLength);
        realByteBuffer.put(bytes);
        return realByteBuffer;
    }



    public abstract void doMessageBuilder(ByteBuffer byteBuffer,Message message)throws IOException ;


}
